<template>
  <div style="height: 100%">
  </div>
</template>

<script>
import Format from '@/utils/format'

export default {
  // type  AB  AO  BO
  props: {
    type: {
      type: String,
      default: '',
    },
    xNum: {
      type: Number,
      default: 30,
    }
  },
  data() {
    return {
      markAreas: {},
      charts: '',
      yList: [],
      yList2: [],
      timerList: [],
      seriesList: [{
        itemStyle: {
          normal: {
            lineStyle: {
              width: 63//设置线条粗细
            }
          }
        }
      }],
      monitorName: '',
    }
  },
  computed: {
    user() {
      return this.$store.state.userInfo
    },
    yName() {
      return this.type === 'X' || this.type === 'Y' ? '角度(°)' : '位移(mm)'
    },
    options() {
      var _this = this

      function formatter(params) {
        var contentArr = []
        for (var i = 0; i < params.length; i++) {
          var data = params[i]
          if (i === 0) {
            contentArr.push('孔深：' + data.name + 'm')
          }
          let y = String(data.value).indexOf(".") + 1;//获取小数点的位置
          let count = String(data.value).length - y;//获取小数点后的个数
          if (_this.type == 'X' || _this.type == 'Y' || _this.type == 'az' || _this.type == 'in') {
            if (data.value !== undefined) {
              if (count < 3) {
                contentArr.push(data.marker + data.seriesName + '：' + data.value + '°')
              } else {
                contentArr.push(data.marker + data.seriesName + '：' + data.value.toFixed(3) + '°')
              }
            }


          } else {
            contentArr.push(data.marker + data.seriesName + '：' + data.value.toFixed(3) + 'mm')
          }
        }
        // contentArr.push("<i style='font-size:10px' >提示：点击查看时间位移曲线</i>")
        return contentArr.join('<br/>')
      }

      return {
        title: {
          text: `${this.monitorName}`,
          x: 'center'
        },
        animationDuration: 2000, // 动画时长 可以接受 回调函数
        //提示框组件
        tooltip: {
          position: ['10', '10'],
          // 设置为坐标轴触发
          trigger: 'axis',
          // 提示框悬浮内容格式器
          formatter: formatter
        },
        // 图例组件
        legend: {
          data: this.timerList,
          y: 'top',
          x: 'right',
          padding: [60, 5, 0, 0],
          // 设置为可滚动的图例
          type: 'scroll',
          orient: 'vertical'
        },
        // 直角坐标系内绘图网格
        grid: {
          left: 50,
          right: 220,
          bottom: 40,
          // 区域是否包含坐标轴的刻度标签
          containLabel: false
        },
        // 工具栏。内置有导出图片，数据视图，动态类型切换，数据区域缩放，重置五个工具。
        toolbox: {
          // 各个工具配置
          feature: {
            // 保存为图片
            saveAsImage: {}
          }
        },
        // grid x轴
        yAxis: [{
          splitLine: {
            show: true
          },
          // 坐标轴名称
          name: '孔深(m)',
          // 类型为类目轴适用于离散的类目数据。为该类型时类目数据可自动从 series.data 或 dataset.source 中取，或者可通过 xAxis.data 设置类目数据。
          type: 'category',
          boundaryGap: false,
          // 数据
          data: this.yList
        },
          {
            // 坐标轴名称
            name: '岩性(m)',
            // 类型为类目轴适用于离散的类目数据。为该类型时类目数据可自动从 series.data 或 dataset.source 中取，或者可通过 xAxis.data 设置类目数据。
            type: 'category',
            boundaryGap: false,
            // 数据
            data: this.yList2
          }
          ],
        xAxis: {
          max: function (value) {
            if (value.max < _this.xNum) {
              return _this.xNum
            }
            return Math.ceil(value.max)// 向上取整
          },
          min: function (value) {
            if (value.min > -_this.xNum) {
              return -_this.xNum
            }
            return Math.ceil(value.min)// 向上取整
          },
          type: 'value',
          name: this.yName,
          nameTextStyle:{
            padding: [0, 0, 0, 20]
          },
        },
        series: this.seriesList
      }
    }
  },

  methods: {
    updateEchart(list, holeDepth = 0, colorList,) {
      const keyMap = {
        AB: 'relativeSynthesis',
        AO: 'relativeA0',
        BO: 'relativeB0',
        X: 'xAngle',
        Y: 'yAngle',
        az: 'az',
        in: 'in'
      }
      const markLine = {
        data: this.markLine,
        lineStyle: {
          normal: {
            type: 'dashed',
          }, width: 15
        }
      }
      let yList = list[0]?.sbwyDetails?.map(x => x.depth) || []
      this.yList = [holeDepth, ...yList]
      let timerList = []
      let seriesList = []
      this.yList2 = []
      this.markAreas = {}
      var item2 = {}
      //设置岩性分布Y轴数组
      let yList2 = []
      if(!colorList){
        colorList=[]
      }
      colorList.map((x, index) => {
        yList2.push(x.startDepth, x.endDepth)
      })
      let union = Array.from(new Set([...yList, ...yList2]))//取岩性分布深度和节点深度并集数组
      this.yList2 = [holeDepth, ...union]
      //过滤排序重复数组
      function checkArray(arr) {
        var result = [];
        for (var i = 0, len = arr.length; i < len; i++) {
          if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
          }
        }
        return result.sort(function (a, b) {
          return a - b;
        });
      }
      this.yList2 = checkArray(this.yList2)
      this.yList2.reverse()
      list.map((x, i) => {
        let timer = Format(new Date(x.createTime))
        timerList.push(timer)
        if (colorList !== undefined) {
          let markData = []
          markData = []
          colorList.map(x => {
            //判断显示是岩还是土
            let markDataName
            if (x.lithology == 1) {
              markDataName = '岩质;'+ x.remark
            } else {
              markDataName = '土质;' + x.remark
            }
            markData.push([{
              yAxis: x.startDepth + '',
              name: markDataName,
              label: {
                show: true,
                fontSize:24,
                position: "insideBottom", // markArea中文字（name）位置
                // offset: [0, -80], // markArea中文字（name）显示在位置基础上x、y轴偏移
                color: "rgba(21,21,21,0.64)" // markArea中文字（name）颜色
              },
              itemStyle: {
                color: x.colorVal + '',
                opacity: 0.02 //控制颜色
              }
            },
              {yAxis: x.endDepth + ''}])
          })
          this.markAreas = {//设置具体区域的背景颜色，选择不同区间 设置图表对应的背景颜色
            silent: true,
            data: markData
          }
        }
        let item = {
          name: timer,
          splitNumber: 0.5,
          yAxisIndex: 0, //双y轴设置使用哪个y轴的值
          type: 'line',
          smooth: true,
          label: this.type,
          data: [0, ...x.sbwyDetails.map(w => w[keyMap[this.type]])],
          animation: true, // 是否开启动画 默认为true
          addDataAnimation: true,
        }
        item2 = {
          yAxisIndex: 1, //双y轴设置使用哪个y轴的值
          type: 'line',
          splitNumber: 0.5,
          label: this.type,
          markArea: this.markAreas
        }
        if (i === 0) item.markLine = markLine
        seriesList.push(item)
        seriesList.push(item2)
      })
      this.timerList = timerList
      this.seriesList = seriesList
      this.charts.clear()
      this.charts.resize()
      this.charts.setOption(this.options, true)
    },
    // echart随着窗口改变
    echartResize() {
      this.charts.resize()
    }
  },
  created() {
    const titleMap = {
      AB: '合成方向相对位移',
      AO: 'AO方向相对位移',
      BO: 'BO方向相对位移',
      X: 'X角度',
      Y: 'Y角度',
      az: 'az',
      in: 'in'

    }
    this.monitorName = titleMap[this.type]
  },
  mounted() {
    const Echarts = require('echarts')
    this.charts = Echarts.init(this.$el, null, {locale: 'ZH'})
    this.charts.on('click', params => {
      // 关闭tip提示
      this.charts.dispatchAction({type: 'hideTip'})
      this.$emit('showDialog', {params, type: this.type})
    })
    this.charts.on('mouseout', params => {
      // 关闭tip提示
      this.charts.dispatchAction({type: 'hideTip'})
    })
    window.addEventListener('resize', this.echartResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.echartResize)
  }
}
</script>
